package com.wx.disparent.mallparent.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageInfo;
import com.wx.disparent.mallparent.commons.util.PageResult;
import com.wx.disparent.mallparent.entity.MerchantEntity;
import com.wx.disparent.mallparent.entity.OrderEntity;
import com.wx.disparent.mallparent.entity.ProductEntity;
import com.wx.disparent.mallparent.entity.UserEntity;
import com.wx.disparent.mallparent.service.OrderService;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 曾右权
 * @description
 * @date 2019/12/11 9:34
 */
@RestController
@RequestMapping("/admin/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    private final static Logger logger = LoggerFactory.getLogger(OrderController.class);

    /**
     * 获取所有订单信息
     * @return 订单集合
     */
    @RequestMapping("/getAll")
    public ModelAndView getAll() {
        ModelAndView model = new ModelAndView();
//        if (id==null||id.equals("")){
//            model.setViewName("/web/pc/orderPage");
//            return model;
//        }else {
//            List<OrderEntity> entities = orderService.findAll(null);
//            model.addObject("orders", entities);
            model.setViewName("web/pc/orderPage");
            return model;
//        }

    }

    /**
     * 确认收货
     *
     * @param orderEntity 订单信息
     * @return 执行结果 0失败
     */
    @RequestMapping("/orderConfirmReceipt")
    public String orderConfirmReceipt(OrderEntity orderEntity) {
        return "" + orderService.update(orderEntity, 1);
    }

    /**
     * 查询下级订单
     * @param referId 上级用户ID
     * @return 订单集合
     */
    @RequestMapping("/getAllByReferId")
    public ModelAndView getAllByReferId(@RequestParam(value = "referId") String referId) {
        ModelAndView model = new ModelAndView();
//        Map<String, Object> paramMap = new HashMap<String, Object>();
////        获取上级用户id
//        if (referId != null && !referId.equals("")){
//            System.out.println(referId);
//            paramMap.put("referId", referId);
//            List<OrderEntity> all = orderService.findAll(paramMap);
//            model.addObject("orders", all);
            model.setViewName("web/pc/orderPageSubordinate");
//        }else {
//            model.setViewName(null);
//        }
        return model;
    }

    /**
     * 确认用户支付
     * @param orderEntity 订单信息
     * @return 执行结果 0失败
     */
    @RequestMapping("/orderConfirmUserPay")
    public String orderConfirmUserPay(OrderEntity orderEntity) {
        return "" + orderService.update(orderEntity, 2);
    }

    /**
     * 查询商家账号
     * @param orderId
     * @return 执行结果 0失败
     */
    @RequestMapping("/findMerchantEntityAccout")
    public ModelAndView findMerchantEntityAccout(@RequestParam(value = "orderId") Integer orderId,@RequestParam(value = "productId") Integer productId) {
        OrderEntity orderEntity = orderService.findById(orderId);
        MerchantEntity merchantEntity = orderService.findMerchantEntityAccout(productId);
        ModelAndView mv = new ModelAndView();
        mv.addObject("merchantEntity",merchantEntity);
        mv.addObject("orderEntity",orderEntity);
        mv.setViewName("web/pc/referOrderGeneratePay");
        return mv;
    }

    /**
     * 跳转到等待商家户确认
     * @param orderId 订单信息
     * @return 执行结果 0失败
     */
    @RequestMapping("/referAfterPay")
    public ModelAndView referAfterPay(@RequestParam(value = "orderId") Integer orderId) {
        ModelAndView modelAndView = new ModelAndView();
        OrderEntity orderEntity = orderService.findById(orderId);
        orderService.update(orderEntity,5);
        modelAndView.addObject("orderId",orderId);
        modelAndView.setViewName("web/pc/referAfterPay");
        return modelAndView;
    }

    /**
     * 查询订单
     * @param orderId 订单id
     * @return 执行结果 0失败
     */
    @RequestMapping("/findOrderEntityByOrderId")
    public OrderEntity findOrderEntityByOrderId(Integer orderId) {
//        System.out.println(orderId);
        return orderService.findById(orderId);
    }


    /**
     * 确认中间用户支付
     * @param orderEntity 订单信息
     * @return 执行结果 0失败
     */
    @RequestMapping("/orderConfirmReferPay")
    public String orderConfirmReferPay(OrderEntity orderEntity) {
        return "" + orderService.update(orderEntity, 3);
    }

    /**
     * 分页查询测试
     * @return 分页订单集合
     */
   /* @RequestMapping("/getAllTest")
    public PageInfo list(HttpServletRequest request, HttpServletResponse response) {
//        Map<String, Object> paramMap = new HashMap<String, Object>();
//        int pageSize = PageUtil.getPage(request, "pageSize");
//        int pageNum = PageUtil.getPage(request, "pageNum");
        int pageSize = 2;
        int pageNum = 1;
//        String name = request.getParameter("name") == null || request.getParameter("name").equals("") ? "" : request.getParameter("name");
//        logger.debug("pageNum:" + pageNum + " pageSize:" + pageSize);
//        paramMap.put("name", name);

        PageInfo<OrderEntity> pageInfo = orderService.findAll(null, pageNum, pageSize);
        for (int i = 0; i < pageInfo.getList().size(); i++) {
            System.out.println(pageInfo.getList().get(i).getId());
        }
        return pageInfo;
    }*/

    /**
     * 跳转到修改发货状态页面
     * @param orderId 订单id
     * @return 订单信息
     */
    @RequestMapping("/updateConsignStatus")
    public ModelAndView updateConsignStatus(@RequestParam(value = "id", required = false) Integer orderId) {
        ModelAndView model = new ModelAndView();
//        查询订单信息
        OrderEntity  orderEntity = orderService.findById(orderId);
        model.addObject("order", orderEntity);
        model.setViewName("web/pc/updateConsignStatus");
        return model;
    }

    /**
     * 修改发货状态
     * @param orderEntity 订单
     * @return 修改结果 0失败
     */
    @RequestMapping(value = "/updateOrderConsignStatus", method = RequestMethod.POST)
    public String updateOrderConsignStatus(OrderEntity orderEntity) {
        return ""+orderService.update(orderEntity,0);
    }

    /**
     * 获取下级订单信息 （分页查询）
     *
     * @return 下级订单
     */
    @RequestMapping("/pageTable")
    public String pageTable(@RequestParam("aoData") String aoData, HttpSession httpSession) {
        PageResult pr = new PageResult(aoData);
        String search = pr.getSearch();

        JSONArray jsonArray = new JSONArray();
        List<OrderEntity> entities;
        UserEntity userEntity = (UserEntity) httpSession.getAttribute("userEntity");
//        if (search.equals("")) {
//            entities = orderService.findAll(null);
//        } else {
        Map<String, Object> map = new HashMap<>();
        map.put("referId", userEntity.getId());
        map.put("payStatus", "12");
        entities = orderService.findAll(map);
//        }

        for (Object obj : entities) {
            OrderEntity entity = (OrderEntity) obj;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", entity.getId());
            jsonObject.put("productName", entity.getProductEntityName());
            jsonObject.put("totalNum", entity.getTotalNum());
            jsonObject.put("payMoney", entity.getPayMoney());
            jsonObject.put("payStatus", entity.getPayStatus());
            jsonObject.put("referPayMoney", entity.getReferPayMoney());
            jsonObject.put("referPayStatus", entity.getReferPayStatus());
            jsonObject.put("welfareMoney", entity.getWelfareMoney());
            jsonObject.put("orderStatus", entity.getOrderStatus());
            jsonObject.put("confirm", entity.getPayStatus());
            jsonObject.put("operate", entity.getReferPayStatus());
            jsonObject.put("productId", entity.getProductId());
            jsonObject.put("details", entity.getId());
            jsonArray.add(jsonObject);
        }

        String json = "{\"sEcho\":" + (pr.getsEcho()+1) + ",\"iTotalRecords\":" + pr.getPage().getTotal() + ",\"iTotalDisplayRecords\":" + pr.getPage().getTotal() + ",\"aaData\":" + jsonArray.toString() + "}";

        return json;
    }


    /**
     * 获取所有订单信息 （分页查询）
     *
     * @return 订单集合
     */
    @RequestMapping("/pageTable1")
    public String pageTable1(@RequestParam("aoData") String aoData, HttpSession httpSession) {
        PageResult pr = new PageResult(aoData);
        String search = pr.getSearch();

        JSONArray jsonArray = new JSONArray();
        List<OrderEntity> entities;
        Map<String, Object> map = new HashMap<>();
        map.put("referPayStatus", "12");
        entities = orderService.findAll(map);
//        }

        for (Object obj : entities) {
            OrderEntity entity = (OrderEntity) obj;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", entity.getId());
            jsonObject.put("productName", entity.getProductEntityName());
            jsonObject.put("totalNum", entity.getTotalNum());
            jsonObject.put("referPayMoney", entity.getReferPayMoney());
            jsonObject.put("referPayStatus", entity.getReferPayStatus());

            jsonObject.put("consignStatus", entity.getConsignStatus());
            jsonObject.put("shippingName", entity.getShippingName());
            jsonObject.put("shippingCode", entity.getShippingCode());
            jsonObject.put("receiverContact", entity.getReceiverContact());
            jsonObject.put("receiverMobile", entity.getReceiverMobile());

            jsonObject.put("receiverAddress", entity.getReceiverAddress());
            jsonObject.put("orderStatus", entity.getOrderStatus());
            jsonObject.put("updateConsignStatus", entity.getConsignStatus());
            jsonObject.put("orderConfirmReferPay", entity.getReferPayStatus());
            jsonObject.put("orderConfirmReceipt", entity.getConsignStatus());
            jsonObject.put("details", entity.getId());
            jsonArray.add(jsonObject);
        }

        String json = "{\"sEcho\":" + (pr.getsEcho()+1) + ",\"iTotalRecords\":" + pr.getPage().getTotal() + ",\"iTotalDisplayRecords\":" + pr.getPage().getTotal() + ",\"aaData\":" +  JSONObject.toJSONString(jsonArray, SerializerFeature.WriteMapNullValue) + "}";

        return json;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public ModelAndView findById(@RequestParam(value = "id") Integer id) {
        ModelAndView model = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        OrderEntity orderEntity = orderService.findById(id);
        model.addObject("order", orderEntity);
        model.setViewName("web/pc/orderOnePage");
        return model;
    }

    /**
     * 查询下级订单详情
     * @param id
     * @return
     */
    @RequestMapping("/referFindById")
    public ModelAndView referFindById(@RequestParam(value = "id") Integer id) {
        ModelAndView model = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        OrderEntity orderEntity = orderService.findById(id);
        model.addObject("order", orderEntity);
        model.setViewName("web/pc/orderOnePageSubordinate");
        return model;
    }

}
